/*
 * 文 件 名:  BatchUploadAction.java
 * 版    权:   深圳埃思欧纳信息咨询有限公司版权所有. YYYY-YYYY,  All rights reserved
 * 描    述:   <描述>
 * 修 改 人:  honny.huang
 * 修改时间: 2011-6-11
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.fileUpload.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.common.ServiceConstants;
import com.fileUpload.form.BatchUploadForm;
import com.fileUpload.utilities.EncryptorTool;
import com.fileUpload.utilities.UploadUtil;
import com.fileUpload.utilities.unpack.ExtractRarArchive;
import com.fileUpload.utilities.unpack.ExtractZipArchive;
import com.sun.jmx.remote.util.Service;

/**
 * <获取上传的文件，将文件数据存入数据库中> <功能详细描述>
 *
 * @author honny.huang
 * @version [版本号, 2011-6-11]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */

public class BatchUploadAction extends Action{
	
	  public static String LASTUPLOADTIME = "lastUploadTime";

	  public static String LASTUPLOADFILENAME = "lastUploadFileName";

	    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
	            HttpServletResponse response) throws Exception
	    {
	    	//设置输出格式
	    	response.setContentType("text/html;charset=UTF-8");
	    	PrintWriter out = response.getWriter();
	        // 定义返回信息
	        String errorMessage = "";
	        String infoMsg = "";
	        String resultData = null;
	        boolean falg = true;

	        
	        // 输入输出流
	        InputStream streamIn = null;
	        OutputStream streamOut = null;
	        String[] fileTypes = new String[]{"rar", "zip", "doc", "txt", "pdf", "rtf", "ppt", "jpg", "xls", "html", "mht", "htm"};
//	        String[] fileTypes = AceonaConfig.getConfig(ConfigKeys.RESUME_TYPE).split(",");
	        //允许上传文件大小
//	        int size_limit = Integer.parseInt(AceonaConfig.getConfig(ConfigKeys.BATCH_RESUME_SIZE_LIMIT));
	        int size_limit = Integer.parseInt(ServiceConstants.UploadStatus.Upload_SIZE_LIMIT.value);
	        
	        // 没有简历，直接转入上传页面
	        int fileSize = 0;
	        List<String> newResumeNames = null;
	        List<String> oldResumeNames = null;
	        List<FormFile> files = new ArrayList<FormFile>();
	        
            BatchUploadForm batchUploadForm = (BatchUploadForm) form;
            FormFile batchUploadFile = batchUploadForm.getBatchUploadFile();
            if (batchUploadFile == null)
            {
                errorMessage = "没有选择上传文件！";
                resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
    	        out.println(resultData);
    	        return null;
            }else
        	{
//	            	String savingPath = AceonaConfig.getConfig(ConfigKeys.RESUME_SAVE_CATALOG) + "/" + userSession.getAccountID();
            	//保存在web根目录下的test目录下
            	String savingPath =  request.getRealPath("/") + "test";
		        File fileVar = new File(savingPath);   //path :\opt\Aceona\resume\test
            	// 文件大小
            	fileSize = batchUploadFile.getFileSize();
            	// 文件名称
                String fileOldName = batchUploadFile.getFileName().trim();
    	        String lastUploadFileNameString = (String) request.getSession(Boolean.TRUE).getAttribute(LASTUPLOADFILENAME);

                if (null != fileOldName && !"".equals(fileOldName))
                {
//                	if(fileOldName.equalsIgnoreCase(lastUploadFileNameString))
//                	{
//                		errorMessage = "请勿重复上传相同文件";
//                        resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
//    	    	        out.println(resultData);
//    	    	        return null;
//                	}
//                	 // 刷新最后上传文件内容
//                    request.getSession(Boolean.TRUE).setAttribute(LASTUPLOADFILENAME, fileOldName);
                    // 判断文件类型
                    if (!UploadUtil.checkTypes(fileTypes,fileOldName.split("\\.")))
                    {
                    	errorMessage = "您上传的文件类型不正确;请导入以下类型的文件:";
                        for (int i = 0; i < fileTypes.length; i++) {
                        	errorMessage+="*." + fileTypes[i] + " ";   
						}  
                        resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
    	    	        out.println(resultData);
    	    	        return null;
                    }
                    // 1，如果文件类型为rar,则解压缩文件,并返回文件列表结果集
                    // 2,为压缩包上传则添加解压文件后结果集到上传内容中
                    if (UploadUtil.TYPERAR.equalsIgnoreCase(UploadUtil.subFileType(fileOldName)))
                    {
                        List<FormFile> listFile = ExtractRarArchive.extractArchive(batchUploadFile);
                        if (null != listFile && listFile.size() > 0)
                        {
                            for (FormFile file : listFile)
                            {
                                files.add(file);
                            }
                        }
                        else {
                        	errorMessage = "您上传的压缩包中没有符合格式的文件！";
         	                resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
         	    	        out.println(resultData);
         	    	        return null;
						}
                    }
                    // 1，如果文件类型为zip,则解压缩文件,并返回文件列表结果集
                    // 2,为压缩包上传则添加解压文件后结果集到上传内容中
                    else if (UploadUtil.TYPEZIP.equalsIgnoreCase(UploadUtil.subFileType(fileOldName)))
                    {
                        List<FormFile> listFile = ExtractZipArchive.extractArchive(batchUploadFile);
                        if (null != listFile && listFile.size() > 0)
                        {
                            for (FormFile file : listFile)
                            {
                                files.add(file);
                            }
                        }
                        else {
                        	errorMessage = "您上传的压缩包中没有符合格式的文件！";
         	                resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
         	    	        out.println(resultData);
         	    	        return null;
						}
                    }
                    else
                    {
                        files.add(batchUploadFile);
                    }
                }
                // 判断文件大小
                if (fileSize <= 0 || fileSize > size_limit * 1024)
	            {
                	errorMessage = fileSize <=0 ? "文件内容为空" : "文件尺寸超过规定大小:" + size_limit * 1024 + "字节";
	                resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
	    	        out.println(resultData);
	    	        return null;
	            }
	            else
	            {
	            	newResumeNames = new ArrayList<String>();
	            	oldResumeNames = new ArrayList<String>();
	                for (FormFile resumeFile : files)
	                {
	                	// 获取单个文件的文件名
	                    String resumeOldName = resumeFile.getFileName();
	                    oldResumeNames.add(resumeOldName);
	                    // 给文件重新命名
	                    String resumeNewName = Calendar.getInstance().getTimeInMillis() + "."
	                            + resumeOldName.split("\\.")[resumeOldName.split("\\.").length - 1];
	                    if (!fileVar.exists())
	                    {
	                        try
	                        {
	                            fileVar.mkdirs();
	                        }
	                        catch (Exception e)
	                        {
//		                            logger.error(e.getMessage());
	                            throw e;
	                        }
	                    }
	                    try
	                    {
	                        streamIn = resumeFile.getInputStream();
	                        streamOut = new FileOutputStream(savingPath + "/" + resumeNewName);
	                        // 加密FileInputStream fis，通过FileOutputStream fos输出
	                        EncryptorTool.encryptFileInputStrean(streamIn, streamOut);
	                        // 将新命名的文件添加到list中
	                        newResumeNames.add(resumeNewName);
	                    }
	                    catch (Exception ex)
	                    {
	                        for (String savedResumeName : newResumeNames)
	                        {
	                            fileVar = new File(savingPath + "/" + savedResumeName);
	                            if (fileVar.exists())
	                            {
	                                try
	                                {
	                                    fileVar.delete();
	                                }
	                                catch (Exception e)
	                                {
//		                                    logger.error(e.getMessage());
	                                }
	                            }
	                        }
	                    }
	                    finally
	                    {
	                    	// 关闭文件流
	                        if (streamOut != null)
	                        {
	                            streamOut.close();
	                        }
	                        if (streamIn != null)
	                        {
	                            streamIn.close();
	                        }
	                    }
	                }
	            }
            }
            
//	            returnCode = ReturnCode.SUCCESS;
            if (falg)
            {
            	// 定义操作成功信息
//	                infoMsg = "上传成功,简历审核中...";
                infoMsg = "uploadSuccess";
                resultData = "{\nmsg:'" + infoMsg + "'\n}";
            }
            else
            {
            	errorMessage = "";
                resultData = "{\nerrorMessage:'" + errorMessage + "'\n}";
            }
	            
	        out.println(resultData);
	        out.flush();
	        out.close();
	        return null;
	    }

}
